package licence

import (
	"strconv"
	"strings"
)

const (
	i_Testing         = 0
	i_UseQRCode       = 1
	i_UseQRCodeCount1 = 2  // 允许1次
	i_UseQRCodeCount3 = 3  // 允许3次 (与允许1次叠加后，变成允许5次)
	i_AllowRD         = 26 // R带(核型)
	i_AllowYS         = 27 // 羊水(核型)
	i_AllowPB         = 28 // 外周血(形态/核型)
	i_AllowBM         = 29 // 骨髓(形态/核型)
)

type Parameters struct {
	Testing        bool // [0] true:测试版 false:正式版
	UseQRCode      bool // [1] true:强制使用玻片二维码
	UseQRCodeCount int  // [2-3] 允许使用二维码的次数 (0, 1, 3, 5) (0:无限制)
	AllowRD        bool // [26] R带(核型) (True:允许)
	AllowYS        bool // [27] 羊水(核型) (True:允许)
	AllowPB        bool // [28] 外周血(形态/核型) (True:允许)
	AllowBM        bool // [29] 骨髓(形态/核型) (True:允许)
}

func (p Parameters) str34() string {

	b := ""
	for len(b) < 30 {
		b += "0"
	}

	bb := strings.Split(b, "")

	// 是否为测试环境
	if p.Testing {
		bb[i_Testing] = "1"
	}

	// 是否强制使用二维码
	if p.UseQRCode {
		bb[i_UseQRCode] = "1"
	}

	// 二维码允许使用的次数
	if p.UseQRCode {
		if p.UseQRCodeCount == 1 {
			bb[i_UseQRCodeCount1] = "1"
		}
		if p.UseQRCodeCount == 3 {
			bb[i_UseQRCodeCount3] = "1"
		}
		if p.UseQRCodeCount == 5 {
			bb[i_UseQRCodeCount1] = "1"
			bb[i_UseQRCodeCount3] = "1"
		}
	}

	if p.AllowPB {
		bb[i_AllowPB] = "1"
	}
	if p.AllowBM {
		bb[i_AllowBM] = "1"
	}
	if p.AllowYS {
		bb[i_AllowYS] = "1"
	}
	if p.AllowRD {
		bb[i_AllowRD] = "1"
	}

	s := ""

	for _, v := range bb {
		s += v
	}

	n, _ := strconv.ParseInt(s, 2, 32)

	return str34(int(n), 6)
}

/*
解析参数
*/
func parseParameters(str34 string) (params Parameters, err error) {

	b := strconv.FormatInt(int64(int34(str34)), 2)

	for len(b) < 30 {
		b = "0" + b
	}

	bb := strings.Split(b, "")

	params.Testing = bb[i_Testing] == "1"

	params.UseQRCode = bb[i_UseQRCode] == "1"

	if params.UseQRCode {
		params.UseQRCodeCount = 0
		if bb[i_UseQRCodeCount1] == "1" {
			params.UseQRCodeCount = 1
		}
		if bb[i_UseQRCodeCount3] == "1" {
			params.UseQRCodeCount = 3
		}
		if bb[i_UseQRCodeCount1] == "1" && bb[i_UseQRCodeCount3] == "1" {
			params.UseQRCodeCount = 5
		}
	}

	params.AllowRD = bb[i_AllowRD] == "1"
	params.AllowYS = bb[i_AllowYS] == "1"
	params.AllowPB = bb[i_AllowPB] == "1"
	params.AllowBM = bb[i_AllowBM] == "1"

	return
}
